package com.villaday.idf.activity;

import android.os.Bundle;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.gson.Gson;
import com.villaday.idf.R;
import com.villaday.idf.adapter3.AddressPopularAdapter;
import com.villaday.idf.adapter3.MyWineShopAdapter;
import com.villaday.idf.base.AbsRecyclerViewAdapter;
import com.villaday.idf.base.BaseActivity;
import com.villaday.idf.base.OnAdapterCallbackListener;
import com.villaday.idf.custom.CustomPopupWindow;
import com.villaday.idf.custom.LoadDialog;
import com.villaday.idf.model3.HashFiltersEntity;
import com.villaday.idf.model3.HashHousesEntity;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.LogUtil;
import com.villaday.idf.util.OkHttpUtil;
import com.villaday.idf.util.SharedPreferencesUtil;
import com.villaday.idf.util.ToastUtil;
import com.villaday.idf.util.ToolBarUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class MyWineShopActivity extends BaseActivity {


    @BindView(R.id.toolbar_back)
    ImageButton toolbarBack;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.toolbar_next)
    TextView toolbarNext;
    @BindView(R.id.Line_view)
    View LineView;
    @BindView(R.id.toolbar_text)
    Toolbar toolbarText;
    @BindView(R.id.rv_mws)
    RecyclerView rvMws;
    @BindView(R.id.ll_mws_left)
    LinearLayout llMwsLeft;
    @BindView(R.id.ll_mws_right)
    LinearLayout llMwsRight;
    @BindView(R.id.ll_mws)
    LinearLayout llMws;
    @BindView(R.id.tv_mws_left)
    TextView tvMwsLeft;
    @BindView(R.id.tv_mws_right)
    TextView tvMwsRight;
    @BindView(R.id.tv_mws_not)
    TextView tvMwsNot;
    //    @BindView(R.id.srl_mws)
//    SwipeRefreshLayout srlMws;
    @BindView(R.id.tv_mws_more)
    TextView tvMwsMore;

    private MyWineShopAdapter mMyWineShopAdapter;
    private List<HashHousesEntity.BodyBean.ListBean> mList;
    private boolean isLeft = true;
    private AddressPopularAdapter mHouseManageAdapter;
    private List<HashFiltersEntity.BodyBean> mBody;
    private LoadDialog mLoadDialog;
    private int mPageNo = 1;
    private String mPageSize = "10";
    private String mCity = "";
    private String mDistrict = "";
    private boolean mIsLoadSale = false;
    private int leftPosition = 0;
    private List<String> mTitle;

    @Override
    protected int getViewResId() {
        return R.layout.activity_my_wine_shop;
    }


    @Override
    protected void init() {
        super.init();
        ToolBarUtil.init(toolbarText, "我的酒店", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        showDialog();
        initAdapter();
        getTopTitle();
        getDetail();
    }

    public void initAdapter() {
        rvMws.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mMyWineShopAdapter = new MyWineShopAdapter(this, new OnAdapterCallbackListener() {
            @Override
            public void onCallback() {
                mPageNo++;
                mIsLoadSale = true;
                showDialog();
                getDetail();
            }
        }, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = (int) v.getTag();
                Bundle bundle = new Bundle();
                bundle.putString("houseName", mList.get(position).getName());
                bundle.putString("houseId", mList.get(position).getId());
                switch (v.getId()) {
                    case R.id.tv_mws_left:
                        startActivity(HouseMoneyManageActivity.class, bundle);
                        break;
                    case R.id.tv_mws_right:
                        startActivity(HouseManageActivity.class, bundle);
                        break;
                }
            }
        });
        rvMws.setAdapter(mMyWineShopAdapter);
//        srlMws.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
//            @Override
//            public void onRefresh() {
//                mCity = "";
//                mDistrict = "";
//                getTopTitle();
//                getDetail();
//
//            }
//        });
    }


    private void getTopTitle() {
        Map<String, String> map = new HashMap<>();
        OkHttpUtil.getJSON(this, String.format(Constant.URL.hashFilters, SharedPreferencesUtil.getRoleInfoId(this)), map, new OkHttpUtil.OnDataListener() {
            @Override
            public void onResponse(String url, String json) {
                try {
                    LogUtil.jLog().e(json);
                    if (!TextUtils.isEmpty(json)) {
                        HashFiltersEntity hashFiltersEntity = new Gson().fromJson(json, HashFiltersEntity.class);
                        if (hashFiltersEntity.getCode().equals(Constant.Strings.SUC)) {
                            mBody = hashFiltersEntity.getBody();

                            mTitle = new ArrayList<>();
                            for (int i = 0; i < mBody.size(); i++) {
                                mTitle.add(mBody.get(i).getName());

                                if (i > 0) {
                                    if (mBody.get(i).getChildren() != null && mBody.get(i).getChildren().size() > 0) {
//                                        mBody.get(i).getChildren().add(0, "全部");
                                    } else {
                                        mBody.get(i).getChildren().add("全部");
                                    }
                                }
                            }

//                            LogUtil.jLog().e(new Gson().toJson(mBody));
//                            tvMwsLeft.setText(mBody.get(0).getName());
//                            tvMwsRight.setText(mBody.get(0).getChildren().get(0).equals("") ? "行政区" : mBody.get(0).getChildren().get(0));
                        } else {
                            ToastUtil.initToast(getApplicationContext(), hashFiltersEntity.getMsg());
                            dismissDialog();
                        }
                    } else {
                        dismissDialog();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }


            }

            @Override
            public void onFailure(String url, String error) {

            }
        });
    }


    private void getDetail() {
        Map<String, String> map = new HashMap<>();
        map.put("pageNo", mPageNo + "");
        map.put("pageSize", mPageSize);
        map.put("city", mCity.equals("全部") ? "" : mCity);
        map.put("district", mDistrict.equals("全部") ? "" : mDistrict);
        LogUtil.jLog().e(new Gson().toJson(map));

        OkHttpUtil.getJSON(this, String.format(Constant.URL.hashHouses, SharedPreferencesUtil.getRoleInfoId(this)), map, new OkHttpUtil.OnDataListener() {
            @Override
            public void onResponse(String url, String json) {
                try {
                    LogUtil.jLog().e(json);
                    dismissDialog();
                    if (!TextUtils.isEmpty(json)) {
                        HashHousesEntity hashHousesEntity = new Gson().fromJson(json, HashHousesEntity.class);
                        if (hashHousesEntity.getCode().equals(Constant.Strings.SUC) && hashHousesEntity.getBody().getList().size() > 0) {
                            rvMws.setVisibility(View.VISIBLE);
                            tvMwsNot.setVisibility(View.GONE);
                            if (mPageNo > 1 && mIsLoadSale) {
                                mIsLoadSale = false;
                                mList.remove(mList.size() - 1);
                                for (int i = 0; i < hashHousesEntity.getBody().getList().size(); i++) {
                                    hashHousesEntity.getBody().getList().get(i).setShowType(0);
                                    mList.add(hashHousesEntity.getBody().getList().get(i));
                                }

                                if (!hashHousesEntity.getBody().isHasNext()) {
//                                    tvMwsMore.setTextColor(getResources().getColor(R.color.colorTextLight));
//                                    tvMwsMore.setVisibility(View.VISIBLE);
//                                    tvMwsMore.setText("没有更多了");
                                    mList.add(new HashHousesEntity.BodyBean.ListBean(2));
                                } else {
                                    tvMwsMore.setVisibility(View.GONE);
                                    mList.add(new HashHousesEntity.BodyBean.ListBean(1));
                                }
                                mMyWineShopAdapter.notifyDataSetChanged();
                            } else {
                                for (int i = 0; i < hashHousesEntity.getBody().getList().size(); i++) {
                                    hashHousesEntity.getBody().getList().get(i).setShowType(0);
                                }
                                mList = hashHousesEntity.getBody().getList();
                                if (!hashHousesEntity.getBody().isHasNext()) {
//                                    tvMwsMore.setTextColor(getResources().getColor(R.color.colorTextLight));
//                                    tvMwsMore.setVisibility(View.VISIBLE);
//                                    tvMwsMore.setText("没有更多了");
                                    mList.add(new HashHousesEntity.BodyBean.ListBean(2));
                                } else {
                                    tvMwsMore.setVisibility(View.GONE);
                                    mList.add(new HashHousesEntity.BodyBean.ListBean(1));
                                }
                                mMyWineShopAdapter.setData(mList);
                            }
                        } else {
                            rvMws.setVisibility(View.GONE);
                            tvMwsNot.setVisibility(View.VISIBLE);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String url, String error) {

            }
        });

    }


    @OnClick({R.id.ll_mws_right, R.id.ll_mws_left})
    public void btnOnclick(View view) {
        switch (view.getId()) {
            case R.id.ll_mws_left:
                isLeft = true;
                if (popuSort == null) {
                    initAddressPopu();
                } else {
                    popuSort.getPopupWindow().dismiss();
                }
                break;
            case R.id.ll_mws_right:
                isLeft = false;
                if (popuSort == null) {
                    initAddressPopu();
                } else {
                    popuSort.getPopupWindow().dismiss();
                }
                break;
        }
    }

    private CustomPopupWindow popuSort;

    private void initAddressPopu() {
        popuSort = new CustomPopupWindow.Builder().setheight(LinearLayoutCompat.LayoutParams.MATCH_PARENT)
                .setwidth(LinearLayoutCompat.LayoutParams.MATCH_PARENT)
                .isBlur(true)
                .setActivity(this)
                .setOutSideCancel(false)
                .setRadius(5)
                .setContext(this)
                .setContentView(R.layout.popular_address)
                .setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        popuSort = null;
//                        tvSort.setSelected(false);
                    }
                })
                .builder();
        popuSort.getItemView(R.id.vw_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popuSort.getPopupWindow().dismiss();
            }
        });
        RecyclerView rvAddr = (RecyclerView) popuSort.getItemView(R.id.rv_address);

        initRecycle(rvAddr);
        popuSort.showAsLaction(llMws, Gravity.BOTTOM, 0, 0);
    }


    private void initRecycle(RecyclerView mRvAddress) {
        mRvAddress.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mHouseManageAdapter = new AddressPopularAdapter(this);
        mHouseManageAdapter.setOnItemClickListener(new AbsRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                if (isLeft) {
                    leftPosition = position;
                    mCity = mBody.get(position).getName();
                    tvMwsRight.setText("行政区");
                    mDistrict = "";
                    tvMwsLeft.setText(mBody.get(position).getName());
                    mPageNo = 1;
                    showDialog();
                    getDetail();
                    popuSort.getPopupWindow().dismiss();
                } else {
                    mDistrict = mBody.get(leftPosition).getChildren().get(position);
                    tvMwsRight.setText(mDistrict);
                    mPageNo = 1;
                    showDialog();
                    getDetail();
                    popuSort.getPopupWindow().dismiss();
                }
                LogUtil.jLog().e(leftPosition + "  " + mCity + "   " + mDistrict);
            }
        });
        mRvAddress.setAdapter(mHouseManageAdapter);

        if (mBody != null && mBody.size() > 1) {
            if (isLeft) {
                mHouseManageAdapter.setData(mTitle);
            } else {
                mHouseManageAdapter.setData(mBody.get(leftPosition).getChildren());
            }
        }
    }


    /**
     * 设置加载框
     */
    protected void showDialog() {
        if (mLoadDialog == null) {
            mLoadDialog = LoadDialog.newInstance("加载中");
        }
        mLoadDialog.show(getSupportFragmentManager(), "loading");
    }

    /**
     * 设置加载框
     */
    protected void dismissDialog() {
        if (mLoadDialog != null) {
            mLoadDialog.dismiss();
        }

//        if (srlMws != null && srlMws.isRefreshing()) {
//            srlMws.setRefreshing(false);
//        }
    }

}
